<template>
  <div ref="chartRef" :style="{ width: `${width}vw`, height: `${height}vw` }"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const props = defineProps<{
  width?: number
  height?: number
  chartOptions?: any
}>()

const chartRef = ref(null)
const chartEcharts = ref<any>(null)

function handleResize() {
  if (chartEcharts.value) {
    chartEcharts.value.clear()
    chartEcharts.value.resize({ width: 'auto', height: 'auto' })
    chartEcharts.value.setOption(props.chartOptions)
  }
}

watch(
  () => props.chartOptions,
  (newVal) => {
    if (newVal && chartEcharts.value) {
      chartEcharts.value.clear()
      chartEcharts.value.setOption(props.chartOptions)
    }
  },
  { deep: true, immediate: true }
)

onMounted(() => {
  chartEcharts.value = echarts.init(chartRef.value)
  if (props.chartOptions) {
    chartEcharts.value.setOption(props.chartOptions)
  }
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>
